/**
 * @file        quote_separator.hpp
 * @brief       Defines boost.tokenizer escaped quote functor.
 *
 * @author      Emre Turkay <emreturkay at gmail>
 * @date        Jun.25.2008
 */

#ifndef _QUOTE_SEPARATOR_HPP_
#define _QUOTE_SEPARATOR_HPP_

#include <string>

struct quote_separator
{
    explicit quote_separator()
        : quote_(false)
    {
    }

    void reset()
    {
        quote_ = false;
    }

    template <typename InputIterator, typename Token>
    bool operator()(InputIterator& next, InputIterator end, Token& tok)
    {
        if (!quote_)
            tok = Token();

        while (next != end && std::isspace(*next))
            ++next;

        if (next == end)
            return false;

        if (quote_ || (*next == '"'))
        {
            if (!quote_)
                ++next;
            else
            {
                quote_ = true;
                escape_ = false;
            }

            for (; (next != end) && (*next != '"' || escape_); ++next)
            {
                if (!escape_ && *next == '\\')
                    escape_ = true;
                else
                {
                    tok += *next;
                    escape_ = false;
                }
            }

            if (next == end)
                return false;

            ++next;
            quote_ = false;
        }
        else
        {
            for (; next != end && !std::isspace(*next); ++next)
                tok += *next;
        }

        return true;
    }

private:
    bool quote_;
    bool escape_;
};

#endif // _QUOTE_SEPARATOR_HPP_
